//
//  CustomerAVPlayer.m
//  miaopai
//
//  Created by Crow Zhang on 15/11/19.
//  Copyright © 2015年 Crow Zhang. All rights reserved.
//

#import "CustomerAVPlayer.h"

#define X frame.origin.x
#define Y frame.origin.y
#define Width frame.size.width
#define Height frame.size.height

@interface CustomerAVPlayer()

@property(nonatomic, retain)AVPlayer *player;

@property(nonatomic, retain)UIProgressView *progressView;//播放进度条
@property(nonatomic, assign)id progressViewObserver;//播放进度观察者
@property(nonatomic, assign)AVPlayerLayer *playerLayer;

@property(nonatomic, retain)UIButton *button;

@property(nonatomic, retain)UIButton *finishButton;

@property(nonatomic, retain) UIView *progressBackgroundView;

@property(nonatomic, retain) UISlider *slider;

@property(nonatomic, retain) UILabel *leftLabel;

@property(nonatomic, retain) UILabel *rightLabel;

@property(nonatomic, assign) CGFloat lastTime;

@property(nonatomic, assign)NSInteger touchTime;

@end

@implementation CustomerAVPlayer

-(void)dealloc{
    [_player release];
    [_progressView release];
    [_button release];
    [_finishButton release];
    [_progressBackgroundView release];
    [_slider release];
    [_leftLabel release];
    [_rightLabel release];
    [self removeOberserFromProgressView];
    [self removeNotification];
    [self removeObserverFromPlayerItem:_player.currentItem];
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self createViews];
        [self.player play];
    }
    return self;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self createViews];
    }
    return self;
}



#pragma mark 创建UI
- (void)createViews
{
    self.touchTime = 0;
    
    //self.playURL = ;
    AVPlayerItem *playerItem = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:self.playURL]];
    
    _player = [[AVPlayer alloc]initWithPlayerItem:playerItem];
    [self addNotification];
    [self addObserverToProgressView];
    [self addObserverToPlayerItem:_player.currentItem];
    
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.backgroundColor = [UIColor blackColor].CGColor;
    self.playerLayer.frame = CGRectMake(0, 0, 0, 0);
    [self.layer addSublayer:self.playerLayer];
    
    self.button = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.button addTarget:self action:@selector(clickPlayOrPauseButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.button];
    
    self.finishButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.finishButton setImage:[UIImage imageNamed:@"iconfont-bofangqibofang-2"] forState:UIControlStateNormal];
    [self.finishButton addTarget:self action:@selector(replay) forControlEvents:UIControlEventTouchUpInside];
    
    self.progressBackgroundView = [[UIView alloc] init];
    [self addSubview:_progressBackgroundView];
    [_progressBackgroundView release];
    
    self.progressView = [[UIProgressView alloc] init];
    [_progressBackgroundView addSubview:_progressView];
    [_progressView release];
    
    self.slider = [[UISlider alloc] init];
    [_progressView addSubview:_slider];
    [_slider release];
    
    self.leftLabel = [[UILabel alloc] init];
    _leftLabel.text = @"00:00";
    [_progressBackgroundView addSubview:_leftLabel];
    [_leftLabel release];
    
    self.rightLabel = [[UILabel alloc] init];
    _rightLabel.text = @"00:00";
    [_progressBackgroundView addSubview:_rightLabel];
    [_rightLabel release];
    

}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.playerLayer.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    self.playerLayer.backgroundColor = [UIColor blackColor].CGColor;
    
    self.button.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height - 30);
    self.finishButton.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height - 30);
    
    _progressBackgroundView.frame = CGRectMake(0, self.frame.size.height - 30, self.frame.size.width, 30);
    _progressBackgroundView.backgroundColor = [UIColor blackColor];
    _progressBackgroundView.alpha = 0.7;
    
    _progressView.frame = CGRectMake( 50, 15, _progressBackgroundView.frame.size.width - 100, 30);
    [_progressView setProgressTintColor:[UIColor colorWithRed:0.5678 green:0.5678 blue:0.5678 alpha:1.0]];
    
    _slider.frame = CGRectMake(0, 0, _progressView.frame.size.width, _progressView.frame.size.height);
    _slider.minimumTrackTintColor = [UIColor yellowColor];
    _slider.maximumTrackTintColor = [UIColor clearColor];
    [_slider setThumbImage:NULL forState:UIControlStateHighlighted];
    UIImage *image = [UIImage imageNamed:@"iconfont-yuan-3"];
    image = [self OriginImage:image scaleToSize:CGSizeMake(15, 15)];
    [_slider setThumbImage:image forState:UIControlStateNormal];
    _slider.minimumValue = 0;
    [_slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    
    _leftLabel.frame = CGRectMake(0, 0, _progressView.frame.origin.x, _progressBackgroundView.frame.size.height);
    _leftLabel.textColor = [UIColor whiteColor];
    _leftLabel.backgroundColor = [UIColor clearColor];
    _leftLabel.font = [UIFont systemFontOfSize:13];
    _leftLabel.textAlignment = NSTextAlignmentCenter;
    
    
    _rightLabel.frame = CGRectMake(_progressView.frame.origin.x + _progressView.frame.size.width, _leftLabel.frame.origin.y, _leftLabel.frame.size.width, _leftLabel.frame.size.height);
    _rightLabel.textColor = [UIColor whiteColor];
    _rightLabel.backgroundColor = [UIColor clearColor];
    _rightLabel.font = [UIFont systemFontOfSize:13];
    _rightLabel.textAlignment = NSTextAlignmentCenter;
    
}

-(UIImage*) OriginImage:(UIImage*)image scaleToSize:(CGSize)size

{
    
    UIGraphicsBeginImageContext(size);//size为CGSize类型，即你所需要的图片尺寸
    
    [image drawInRect:CGRectMake(0,0, size.width, size.height)];
    
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return scaledImage;
    
}

#pragma mark slider的监听方法
- (void)sliderAction:(UISlider *)slider
{
    CMTime newTime =  CMTimeMakeWithSeconds(slider.value, 1);
    [_player seekToTime:newTime];
}


//播放完成通知
#pragma mark 添加通知
-(void)addNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinishAction) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}

#pragma mark 播放完成的方法
-(void)playFinishAction{
    //NSLog(@"播放完成");
    [self addSubview:self.finishButton];
}

- (void)replay
{
    self.slider.value = 0;
    self.lastTime = 0.0;
    [[self.player currentItem] seekToTime:kCMTimeZero];
    [self.finishButton removeFromSuperview];
    [self.player play];
}

#pragma mark 移除通知
-(void)removeNotification{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

#pragma mark - 监控播放进度
#pragma mark - 更新播放进度条
-(void)addObserverToProgressView{
    //__block Vie *vc = self;
    AVPlayerItem *currentItem = _player.currentItem;
    
    _progressViewObserver = [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float currentTime = CMTimeGetSeconds(time);
        float totalTime = CMTimeGetSeconds([currentItem duration]);
        //NSLog(@"当前已播放:%.2f", currentTime);
        if (currentTime) {
            //[self.proviessView setProgress:(currentTime / totalTime) animated:YES];
            if ((currentTime - self.lastTime) > 3) {
                [UIView animateWithDuration:0.5 animations:^{
                    self.progressBackgroundView.alpha = 0;
                }];
                self.touchTime = 0;
            }
            
            [self.finishButton removeFromSuperview];
            self.slider.value = currentTime;
            if (currentTime < 60) {
                _leftLabel.text = [NSString stringWithFormat:@"00:%.2ld",(NSInteger)currentTime];
            }else
            {
                NSInteger minute = currentTime  / 60;
                NSInteger second = currentTime  - 60 * minute;
                if (minute < 10) {
                    _leftLabel.text = [NSString stringWithFormat:@"0%ld:%.2ld", minute, second];
                    //NSLog(@"%@", _rightLabel.text);
                }else
                {
                    _leftLabel.text = [NSString stringWithFormat:@"%ld:%.2ld", minute, second];
                    //NSLog(@"%@", _rightLabel.text);
                }
            }
        }
    }];
}

#pragma mark 移除监控
-(void)removeOberserFromProgressView{
    [_player removeTimeObserver:_progressViewObserver];
}


#pragma mark 监控playItem
#pragma mark 添加监控
-(void)addObserverToPlayerItem:(AVPlayerItem *)playerItem{
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];//播放状态
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];//缓冲
}

#pragma mark 移除监控
-(void)removeObserverFromPlayerItem:(AVPlayerItem *)playerItem{
    [playerItem removeObserver:self forKeyPath:@"status"];
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}

#pragma mark 监控中方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    AVPlayerItem *playerItem = object;
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerStatus status = [[change objectForKey:@"new"] integerValue];
        if (status == AVPlayerStatusReadyToPlay) {
            //NSLog(@"正在播放....视频长度:%.2f", CMTimeGetSeconds(playerItem.duration));
            _slider.maximumValue = CMTimeGetSeconds(playerItem.duration);
            NSInteger durationTime = CMTimeGetSeconds(playerItem.duration);
            if (durationTime < 60) {
                _rightLabel.text = [NSString stringWithFormat:@"00:%.2ld",durationTime];
            }else
            {
                NSInteger minute = durationTime  / 60;
                NSInteger second = durationTime  - 60 * minute;
                if (minute < 10) {
                    _rightLabel.text = [NSString stringWithFormat:@"0%ld:%.2ld", minute, second];
                    //NSLog(@"%@", _rightLabel.text);
                }else
                {
                    _rightLabel.text = [NSString stringWithFormat:@"%ld:%.2ld", minute, second];
                   // NSLog(@"%@", _rightLabel.text);
                }
            }
            //self.totalTime = _rightLabel.text;
        }
    }
    else if ([keyPath isEqualToString:@"loadedTimeRanges"]){
        NSArray *array = playerItem.loadedTimeRanges;//缓冲的范围
        CMTimeRange timeRange = [array.lastObject CMTimeRangeValue];
        float startSeconds = CMTimeGetSeconds(timeRange.start);//缓冲开始的时间
        float durationSeconds = CMTimeGetSeconds(timeRange.duration);//缓冲范围
        NSTimeInterval totalBuffer = startSeconds + durationSeconds;
        if ([[_button imageView] image] == nil)
        {
            if(CMTimeGetSeconds(playerItem.currentTime) - totalBuffer < 2){
                [self palyAVPlayer];
            }
        }
        
        //NSLog(@"共缓冲:%.2f", totalBuffer);
        CGFloat totalTime = CMTimeGetSeconds(playerItem.duration);
        [_progressView setProgress:totalBuffer / totalTime animated:YES];
    }
}

#pragma mark 点击方法
#pragma mark 点击播放/暂停按钮
-(void)clickPlayOrPauseButtonAction{
    self.touchTime++;
    if (_player.rate == 1) {
        if (self.touchTime >= 2) {
            [_player pause];
            [self.button setImage:[UIImage imageNamed:@"iconfont-bofangqibofang-2"] forState:UIControlStateNormal];
        }
        
        [UIView animateWithDuration:0.5 animations:^{
            self.progressBackgroundView.alpha = 1;
        }];
        self.lastTime = CMTimeGetSeconds(self.player.currentItem.currentTime);
        
    }
    else{
        [_player play];
        [self.button setImage:nil forState:UIControlStateNormal];
        
    }
}

- (void)setPlayURL:(NSString *)playURL
{
    if (_playURL != playURL) {
        [_playURL release];
        _playURL = [playURL copy];
    }
    NSLog(@"%@", playURL);
    _playerLayer.backgroundColor = [UIColor blackColor].CGColor;
    _slider.value = 0;
    [_button setImage:nil forState:UIControlStateNormal];
    _lastTime = 0.0;
    _leftLabel.text = @"00:00";
    _progressBackgroundView.alpha = 1;
    [_button setImage:nil forState:UIControlStateNormal];
    
    [self removeNotification];
    [self removeObserverFromPlayerItem:_player.currentItem];
    [self removeOberserFromProgressView];
    
    AVPlayerItem *playerItem = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:playURL]];
    [_player replaceCurrentItemWithPlayerItem:playerItem];
    [self addNotification];
    [self addObserverToPlayerItem:playerItem];
    [self addObserverToProgressView];
    [self palyAVPlayer];
    [playerItem release];
}

- (void)setFileURL:(NSString *)fileURL
{
    if (_fileURL != fileURL) {
        [_fileURL release];
        _fileURL = [fileURL copy];
    }
    _playerLayer.backgroundColor = [UIColor blackColor].CGColor;
    _slider.value = 0;
    [_button setImage:nil forState:UIControlStateNormal];
    _lastTime = 0.0;
    _leftLabel.text = @"00:00";
    _progressBackgroundView.alpha = 1;
    [_button setImage:nil forState:UIControlStateNormal];
    [self.player pause];
    [self removeNotification];
    [self removeObserverFromPlayerItem:_player.currentItem];
    [self removeOberserFromProgressView];
    AVPlayerItem *playerItem = [[AVPlayerItem alloc]initWithURL:[NSURL fileURLWithPath:fileURL]];
    NSLog(@"%@", [NSURL fileURLWithPath:fileURL]);
    [_player replaceCurrentItemWithPlayerItem:playerItem];
    [self addNotification];
    [self addObserverToPlayerItem:playerItem];
    [self addObserverToProgressView];
    [playerItem release];
}

- (void)playWithURL:(NSString *)URL
{
    
}


- (void)palyAVPlayer
{
    [self.player play];
    [self.button setImage:nil forState:UIControlStateNormal];
}

- (void)stop
{
    [self.player pause];
    self.progressBackgroundView.alpha = 1;
    self.lastTime = CMTimeGetSeconds(self.player.currentItem.currentTime);
    [self.button setImage:[UIImage imageNamed:@"iconfont-bofangqibofang-2"] forState:UIControlStateNormal];
}

+ (CustomerAVPlayer *)shareCustomerAVPlayer
{
    static CustomerAVPlayer *customerAVPlayer = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        customerAVPlayer = [[CustomerAVPlayer alloc] init];
    });
    return customerAVPlayer ;
}


@end
